<template>
  <div class="app-container">
    <!-- 查询条件开始 -->
    <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="药品名称" prop="medicinesName">
        <el-input
          v-model="queryParams.medicinesName"
          placeholder="请输入药品名称"
          clearable
          size="small"
          style="width:180px"
        />
      </el-form-item>
      <el-form-item label="关键字" prop="keywords">
        <el-input
          v-model="queryParams.keywords"
          placeholder="请输入关键字"
          clearable
          size="small"
          style="width:180px"
        />
      </el-form-item>
      <el-form-item label="药品类型" prop="medicinesType">
        <el-select
          v-model="queryParams.medicinesType"
          placeholder="药品类型"
          clearable
          size="small"
          style="width:180px"
        >
          <el-option
            v-for="dict in medicinesTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="生产厂家" prop="producerId">
        <el-select
          v-model="queryParams.producterId"
          placeholder="生产厂家"
          clearable
          size="small"
          style="width:180px"
        >
          <el-option
            v-for="dict in producerOptions"
            :key="dict.dictValue"
            :label="dict.producerName"
            :value="dict.producerId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="处方类型" prop="prescriptionType">
        <el-select
          v-model="queryParams.prescriptionType"
          placeholder="处方类型"
          clearable
          size="small"
          style="width:180px"
        >
          <el-option
            v-for="dict in prescriptionTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="可用状态"
          clearable
          size="small"
          style="width:180px"
        >
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="cdquery" >重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 查询条件结束 -->

    <!-- 表格工具按钮开始 -->
    <el-row :gutter="10" style="margin-bottom: 8px;">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" @click="del1()">删除</el-button>
      </el-col>
    </el-row>
    <!-- 表格工具按钮结束 -->

    <!-- 数据表格开始 -->
    <el-table  border :data="medicinesTableList"  @selection-change="handleSelectionChnage">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="单位">
              <span>{{ props.row.unit }}</span>
            </el-form-item>
            <el-form-item label="换算量">
              <span>{{ props.row.conversion }}</span>
            </el-form-item>
            <el-form-item label="库存量">
              <span>{{ props.row.medicinesStockNum }}</span>
            </el-form-item>
            <el-form-item label="预警值">
              <span>{{ props.row.medicinesStockDangerNum }}</span>
            </el-form-item>
          </el-form>
		  
        </template>
      </el-table-column>
      <el-table-column label="药品ID" align="center" prop="medicinesId" />
      <el-table-column label="药品名称" align="center" prop="medicinesName" />
      <el-table-column label="药品编号" align="center" prop="medicinesNumber" />
      <!-- :formatter="producterFormatter"-->
      <el-table-column label="生产厂家" width="280px" align="center" prop="producterId" :formatter="producterFormatter"/>
      <!---->
      <el-table-column label="药品类型" align="center" prop="medicinesType" :formatter="medicinesTypeFormatter" />
      <!--  -->
      <el-table-column label="处方类型" align="center" prop="prescriptionType" :formatter="prescriptionTypeFormatter"/>
      <el-table-column label="关键字" align="center" prop="keywords" />
      <el-table-column label="处方价格" align="center" prop="prescriptionPrice" />
      <!---->
      <el-table-column label="状态" prop="status" align="center" :formatter="statusFormatter" />
      <el-table-column label="操作" width="280px" align="center">
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-edit" size="mini"   @click="handleAdd(scope.row)">修改</el-button>
          <el-button type="text" icon="el-icon-delete" size="mini" @click="del(scope.row)" >删除</el-button>
          <el-button type="text" icon="el-icon-plus" size="mini" @click="handleUpdateStorage(scope.row)">调整库存</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 数据表格结束 -->
  <!-- 分页控件开始 -->
  		<el-pagination v-show="total>0" 
		:current-page="pageNum" 
		:page-sizes="[5, 10, 20, 30]"
		 :page-size="pageSize"
  			layout="total, sizes, prev, pager, next, jumper"
			 :total="total" @size-change="handLeSizeChange"
  			@current-change="handleCurrentChange" />
  		<!-- 分页控件结束 -->

    <!-- 添加修改弹出层开始 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="800px"
      center
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="药品名称" prop="medicinesName">
              <el-input v-model="form.medicinesName" style="width:240px" placeholder="请输入药品名称" clearable size="small" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="药品编码" prop="medicinesNumber">
              <el-input v-model="form.medicinesNumber" style="width:240px" placeholder="请输入药品编码" clearable size="small" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="关键字" prop="keywords">
              <el-input v-model="form.keywords" style="width:240px" placeholder="请输入关键字" clearable size="small" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="form.unit" style="width:240px" placeholder="请输入单位" clearable size="small" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="换算量" prop="conversion">
              <el-input v-model="form.conversion" style="width:240px" placeholder="请输入换算量" clearable size="small" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="处方价格" prop="prescriptionPrice">
              <el-input-number v-model="form.prescriptionPrice" style="width:240px" placeholder="请输入处方价格" size="small" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="预警值" prop="medicinesStockDangerNum">
              <el-input-number v-model="form.medicinesStockDangerNum" style="width:240px" placeholder="请输入预警值" size="small" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status" style="width:240px">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                  :value="dict.dictValue"
                >{{ dict.dictLabel }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="药品类型" prop="medicinesType">
              <el-select
                v-model="form.medicinesType"
                style="width:240px"
                placeholder="药品类型"
                size="small"
              >
                <el-option
                  v-for="dict in medicinesTypeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="处方类型" prop="prescriptionType">
              <el-select
                v-model="form.prescriptionType"
                style="width:240px"
                placeholder="处方类型"
                size="small"
              >
                <el-option
                  v-for="dict in prescriptionTypeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生产厂家" prop="producterId">
              <el-select
                v-model="form.producterId"
                style="width:240px"
                placeholder="生产厂家"
                size="small"
              >
                <el-option
                  v-for="d in producerOptions"
                  :key="d.producerId"
                  :label="d.producerName"
                  :value="d.producerId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 添加修改弹出层结束 -->

  </div>
</template>
<script>
	import qs from 'qs';
	import ax from 'axios';
// 引入api
export default {
  // 定义页面数据
  data() {
    return {
      // 是否启用遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 分页数据总条数
      total: 0,
      // 字典表格数据
      medicinesTableList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      // 药品类型数据字典
      medicinesTypeOptions: [],
      // 生产厂家数据
      producerOptions: [],
      // 处方类型数字典
      prescriptionTypeOptions: [],
      // 查询参数
      queryParams: {
        medicinesName: undefined,
        medicinesType: undefined,
        prescriptionType: undefined,
        producerId: undefined,
        status: undefined,
        keywords: undefined
      },
	  pageNum: 1,
	  pageSize: 5,
      delque:[],
	
      // 表单数据
      form: {},
      // 表单校验
      rules: {
        medicinesName: [
          { required: true, message: '药品名称不能为空', trigger: 'blur' }
        ],
        keywords: [
          { required: true, message: '查询关键字不能为空', trigger: 'blur' }
        ],
        prescriptionPrice: [
          { required: true, message: '处方价格不能为空', trigger: 'change' }
        ],
        medicinesStockDangerNum: [
          { required: true, message: '预警值不能为空', trigger: 'change' }
        ],
        medicinesType: [
          { required: true, message: '药品类型不能为空', trigger: 'blur' }
        ],
        prescriptionType: [
          { required: true, message: '处方类型不能为空', trigger: 'blur' }
        ],
        producerId: [
          { required: true, message: '生产厂家不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  // 勾子
  created() {
    // 使用全局的根据字典类型查询字典数据的方法查询字典数据
    this.initMedicinesList();
	this.initStatu();
	this.initMedicinesType();
	this.initPrescriptionType();
	this.initProducer();
  },
  deactivated () {
    //解决vue组件 前进刷新，后退不刷新，
    //$destroy完全销毁一个实例，清理它与其它实例的连接，解绑它的全部指令及事件监听器。
    this.$destroy();
  },

  methods: {
    //批量删除
    del1(row) {
      //axios 请求后台删除该条数据
      //根据唯一的属性去操作对应的数据	stuid
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        //点击 确认
        ax.post(`http://localhost:8886/stock/api/med/del1/` ,this.delque).then(r => {
          if (r.data.t == true) {
            this.$message({
              type: 'success',
              message: '删除成功!',
            });
          }
          this.handleQuery()
        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });


    },
	  
	  del(row) {
	  				//根据唯一的属性去操作对应的数据	stuid 
	  				let stuid = row.medicinesId;
	  					console.log(stuid);
	  				this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
	  					confirmButtonText: '确定',
	  					cancelButtonText: '取消',
	  					type: 'warning'
	  				}).then(() => {
	  					//点击 确认
	  					ax.delete(`http://localhost:8886/stock/api/med/` + stuid).then(r => {
	  						if (r.data.t == true) {
	  							this.$message({			
	  								type: 'success',
	  								message: '删除成功!',
	  							});
	  						}
	  						this.handleQuery()
	  					})
	  
	  				}).catch(() => {
	  					this.$message({
	  						type: 'info',
	  						message: '已取消删除'
	  					});
	  				});
	  				
	  
	  			},
	  // 调整库存
	handleUpdateStorage(row) {
	      const tx = this
          let rid=row.medicinesId;
	      tx.$prompt('请输入要调整[' + row.medicinesName + ']的值', '提示', {
	        confirmButtonText: '确定',
	        cancelButtonText: '取消',
	        inputPattern: /^-?\d+$/,
	        inputErrorMessage: '库存值输入不正确'
	      }).then(({ value }) => {
	        tx.form={
	          medicinesId: rid,
              medicinesStockNum: value
            }
            this.$http.post("/stock/api/med/addStu/",tx.form).then(res => {
	          tx.$message('调整成功')
	          tx.handleQuery()// 重新查询数据
	        }).catch(() => {
	          tx.$message('调整失败')
	        })
	      }).catch(() => {
	        tx.$message('调整取消')
	      })
	    },


	   // 重置表单
	      reset() {
	        this.form = {
	          medicinesId: undefined,
	          medicinesName: undefined,
	          medicinesNumber: undefined,
	          unit: undefined,
	          conversion: undefined,
	          prescriptionPrice: 0,
	          medicinesStockDangerNum: 0,
	          medicinesType: undefined,
	          prescriptionType: undefined,
	          keywords: undefined,
	          medicinesStockNum: 0,
	          status: '0',
			  }
	        },

	  // 取消
	     cancel() {
		   this.reset()
	       this.open = false
	       this.title = ''
		
	     },
	  // 打开添加的弹出层
	  handleAdd(row) {
        if (this.$refs.form != undefined) {
          this.$refs.form.clearValidate();
        }
	    this.open = true
	    this.reset()
	    this.title = '添加生产药品信息'
        this.form=JSON.parse(JSON.stringify(row))
      },

	  // 保存
	  handleSubmit() {
        this.$refs['form'].validate((valid) => {
          if (valid) {
        this.$http.post("/stock/api/med/addStu/",this.form).then(result=>{
	    			        this.$message.success(result.data.msg)
	    			        // 关闭弹出对话框
	    			        this.open = false;
	    			        // 重置表单
	    			        this.reset();
	    			        this.title='';
	    			        //表格回溯到第一页
	    			        this.pageNum=1;
	    			        // 刷新表格数据
	    			        this.initMedicinesList();
	    			    })
                    }
                  })
                },
	  
	  
	  //from表单显示双表关联替换数据//状态
	  			statusFormatter(row){
	  				let v=row.status;
	  				return this.formatDict2(this.statusOptions,v)
	  			},
	  //from表单显示双表关联替换数据//药品类型
				
				medicinesTypeFormatter(row){
					let v=row.medicinesType;
					return this.formatDict2(this.medicinesTypeOptions,v)
				},
	//将字典中的和from表单中的更换显示//处方类型
					prescriptionTypeFormatter(row){
						let v=row.prescriptionType;
						return this.formatDict2(this.prescriptionTypeOptions,v)
					},
	  // 分页pageSize变化时触发
	      handLeSizeChange(val) {
	        this.pageSize = val	
	        // 重新查询
	        this.initMedicinesList()
	      },
	      // 点击上一页  下一页，跳转到哪一页面时触发
	      handleCurrentChange(val) {
	        this.pageNum = val
	        // 重新查询
	        this.initMedicinesList()
	      },
    //重置
    cdquery(){
      this.queryParams={};
      this.pageNum=1;
      this.initMedicinesList();
    },
	  
    // 查询表格数据
    initMedicinesList() {
      // this.loading = true // 打开遮罩 
      this.$http.post("/stock/api/med/semed/"+ this.pageNum+"/"+this.pageSize, this.queryParams).then(result => {
        this.medicinesTableList = result.data.data.records
        this.total = result.data.data.total
        // this.loading = false// 关闭遮罩
      })
    },
	//form表单替换状态
	initStatu() {
		this.$http.get("stock/api/user/findByType/sys_normal_disable").then(result => {
			this.statusOptions = result.data.data
			// this.statusFormatter2=result.data.data
		
		})
	},
	//多选框
	initMedicinesType() {
		this.$http.get("stock/api/user/findByType/his_medicines_type").then(result => {
			this.medicinesTypeOptions=result.data.data
		})
	},
	// //处方类型多选框展示
	initPrescriptionType() {
		this.$http.get("stock/api/user/findByType/his_prescription_type").then(result => {
			this.prescriptionTypeOptions = result.data.data
		
		})
	},
	//生产厂家多选框
	initProducer() {
		this.$http.get("stock/api/user/getAll").then(result => {
					this.producerOptions = result.data.data
					// this.statusFormatter2=result.data.data
		})
	},
	handleQuery(){
		this.pageNum=1;
		this.initMedicinesList();
	},
	//from表单显示双表关联替换数据//生产厂家
				producterFormatter(row){
					let v=row.producterId;
						for(let i=0;i<this.producerOptions.length;i++){
								if(this.producerOptions[i].producerId==v){
									return this.producerOptions[i].producerName;
								}
							}
							return "";
				},
    // 数据表格的多选择框选择时触发
    handleSelectionChnage(val) {
      this.delque=val
    },
   }
}
</script>
<style scoped>
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
</style>
